import { mockAdminLogin, ssoLogin } from "@/api/login";
import { db } from "@/storage";
import { resetRouter, dynamicsRoutes } from "@/router";

export default {
    namespaced: true,
    state: () => ({
        user: {},
        token: "",
        userPermissions: [],
        userPermissionMap: new Map(),
        userMenus: db.get("useMenus") || [],
    }),
    getters: {},
    mutations: {
        async handlerResponse(state, { token, user }) {
            const { userPermissions } = user;
            state.user = user;
            state.userPermissions = userPermissions;
            state.token = token;
            this.commit("user/setStorage");
            this.commit("user/setUserPermissionMap");
            this.commit("user/filterRoutes");
        },
        // 生成PermissionMap
        setUserPermissionMap(state) {
            const permissions = state.userPermissions;
            const map = new Map();
            permissions.forEach((key) => map.set(key, true));
            state.userPermissionMap = map;
            db.setMap("userPermissionMap", map);
        },
        filterRoutes(state) {
            const menus = getLayoutHome().filter((item) =>
                state.userPermissions.includes(item.name)
            );
            state.userMenus = getUserMenus(menus);
            db.set("useMenus", state.userMenus);
        },
        setStorage(state) {
            db.set("token", state.token);
            db.set("user", state.user);
            db.set("expires", new Date().getTime());
        },
    },
    actions: {
        async loginHandler({ commit }, { userName, password, remember }) {
            try {
                const res = await mockAdminLogin({
                    username: userName,
                    password,
                });
                commit("handlerResponse", res);
                return res;
            } catch (err) {
                return err;
            }
        },
        async ssoLoginHandler({ commit }, { token }) {
            try {
                const res = await ssoLogin({ token });
                commit("handlerResponse", res);
                return res;
            } catch (err) {
                return err;
            }
        },
        logout() {
            return new Promise((resovle) => {
                db.clear();
                // 退出重置路由
                resetRouter();
                resovle("Logout Success!");
            });
        },
    },
};

function getLayoutHome() {
    return dynamicsRoutes.map((item) => {
        if (item.path === "/") {
            return item.children[0];
        } else {
            return item;
        }
    });
}

function getUserMenus(menus = []) {
    return menus
        .filter((item) => !(item.meta && item.meta?.hiddenInMenu))
        .map((i) => ({
            ...i,
            children:
                i.children && i.children.length
                    ? getUserMenus(i.children)
                    : undefined,
        }));
}
